<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {ElMessage, ElMessageBox} from 'element-plus'
import { Table } from '@/components/Table'
import { saveTableApi, delTableListApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas  } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import {RecordQueryParams, RecordType} from "@/api/record/types";
import {deleteRecordApi, recordListApi} from "@/api/record";
import {OptionType} from '@/types'
import {useColumnFormat} from "@/hooks/form/useColumnFormat";
import {formatToDateTime} from "@/utils/dateUtil";
import {CreateUserForm, UserEditAdminForm, UserEditForm, UserQueryParams, UserType} from "@/api/user/types";
import {userCreateApi, userDeleteApi, userDisableApi, userEditAdminApi, userListApi} from "@/api/user";
import {deleteUserByIdApi} from "@/api/department";
import {useValidator} from "@/hooks/web/useValidator";
import CryptoJS from "crypto-js";

const ids = ref<string[]>([])

const params: UserQueryParams = {
  page: 1,
  page_size: 10
}
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    params.page = unref(currentPage)
    params.page_size = unref(pageSize)
    const res = await userListApi(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose } = tableMethods

const setSearchParams = (formData: any) => {
  params.name = formData.name
  params.account = formData.account
  getList()
}

const { t } = useI18n()
const types: OptionType[] = [
  {label: '查阅', value: 1, type: 'info'},
  {label: '打印', value: 2, type: 'success'},
]
const roles: OptionType[] = [
  {label: '普通用户', value: 1},
  {label: '医生', value: 2},
  {label: '管理员', value: 99},
]
const {formatOption, formatStatus} = useColumnFormat()
const {required} = useValidator()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'created_at',
    label: '创建时间',
    table: {
      width: 180,
      slots: {
        default: (scope: any)=>{
          const row = scope.row as RecordType
          const time = formatToDateTime(row.created_at, "YYYY-MM-DD hh:mm:ss")
          return <span>{time}</span>
        }
      }
    },
    search: {
      hidden: true,
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'account',
    label: '账号',
    form: {
      colProps: {
        span: 15
      },
      formItemProps: {
      }
    }
  },
  {
    field: 'password',
    label: '密码',
    search: {
      hidden: true
    },
    table: {
      hidden: true,
    },
    form: {
      component: "InputPassword",
      colProps: {
        span: 15
      },
      formItemProps: {
      }
    }
  },
  {
    field: 'name',
    label: '账号名称',
    form: {
      colProps: {
        span: 15
      },
      formItemProps: {
        rules: [required()],
      }
    }
  },
  {
    field: 'is_disabled',
    label: '是否禁用',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (scope: any)=>{
          const row = scope.row as UserType
          return formatStatus(!row.is_disabled)
        }
      }
    },
    form: {
      component: "Switch",
      colProps: {
        span: 15
      }
    }
  },
  {
    field: 'role',
    label: '角色ID',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (scope: any)=>{
          const row = scope.row as UserType
          return formatOption(row.role, roles)
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: roles
      },
      formItemProps: {
        rules: [required()],
      }
    }
  },
  {
    field: 'action',
    width: '200px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as UserType
          return (
            <>
              <BaseButton type="primary" onClick={() => action(data.row, 'edit')} roles={[99]}>
                编辑
              </BaseButton>
              <BaseButton type={row.is_disabled ? 'success' : 'warning'} onClick={() => switchStatus(data.row)}>
                {row.is_disabled ? '启用' : '禁用'}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<UserType | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = '新增用户'
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  await ElMessageBox.confirm("确认删除选中的记录吗", "提示")
  delLoading.value = true
  const promises: Promise<any>[] = []
  unref(ids).forEach(id=>{
    promises.push(userDeleteApi(parseInt(id)))
  })
  await Promise.all(promises)
  // 删除完成
  ElMessage.success('删除完成')
  tableMethods.refresh()
}

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const salt = import.meta.env.VITE_SALT
    const params: CreateUserForm = {
      account: formData.account,
      is_disabled: formData.is_disabled,
      name: formData.name,
      password: CryptoJS.MD5(formData.password + salt).toString(),
      role: formData.role,
    }
    if (actionType.value === 'edit'){
      const e_params: UserEditAdminForm = {
        id: currentRow.value.id,
        account: params.account,
        name: params.name,
        password: params.password,
        role: params.role
      }
      await userEditAdminApi(e_params).finally(()=>saveLoading.value = false)
      ElMessage.success("修改用户成功")
    }else{
      await userCreateApi(params)
          .finally(() => {
            saveLoading.value = false
          })
      ElMessage.success("新增用户成功")
    }
    dialogVisible.value = false
    currentPage.value = 1
    getList()
  }
}
const switchStatus = async(user: UserType)=>{
  await userDisableApi({
    disable: !user.is_disabled,
    id: user.id
  })
  ElMessage.success("操作成功")
  tableMethods.refresh()
}
</script>

<template>
  <ContentWrap title="用户管理">
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton :loading="delLoading" type="primary" @click="AddAction()"  :roles="[99]">
        新增用户
      </BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)"  :roles="[99]">
        删除
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
